<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>订单列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入要查询的订单名"
            v-model="queryInfo.query"
            clearable
            @change="getOrderList"
            @clear="getOrderList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getOrderList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加订单</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="orderlist" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="订单名称" prop="order_name"></el-table-column>
        <el-table-column label="订单日期" prop="order_date"></el-table-column>
        <el-table-column label="订单数量" prop="order_num"></el-table-column>
        <el-table-column label="联系人" prop="order_username"></el-table-column>
        <el-table-column label="手机" prop="order_phone"></el-table-column>
        <el-table-column
          label="订单地址"
          prop="order_address"
        ></el-table-column>
        <el-table-column label="订单方式" prop="order_style"></el-table-column>
        <el-table-column
          label="订单状态"
          prop="order_status"
          :filters="[
            { text: '未发货', value: '未发货' },
            { text: '已发货', value: '已发货' },
          ]"
          :filter-method="filterTag"
          filter-placement="bottom-end"
        >
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.order_status === '未发货' ? 'primary' : 'success'
              "
              disable-transitions
              >{{ scope.row.order_status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- {{ scope.row.id }}  -->
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.order_id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.order_id)"
            ></el-button>
            <!-- 修改订单状态按钮 -->
            <el-tooltip
              effect="dark"
              content="修改订单运输状态"
              placement="top"
              :enterable="false"
              v-if="scope.row.order_status == '已发货'"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setStatus(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加订单的对话框 -->
    <el-dialog
      title="添加订单"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="订单名称" prop="order_name">
          <el-input v-model="addForm.order_name"></el-input>
        </el-form-item>
        <el-form-item label="订单日期" prop="order_date">
          <!-- <el-input v-model="addForm.order_date"></el-input> -->
          <el-date-picker
            v-model="addForm.order_date"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单数量" prop="order_num">
          <el-input v-model="addForm.order_num"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="order_username">
          <el-input
            v-model="addForm.order_username"
            :disabled="currentUserInfo.role !== '管理员'"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="order_phone">
          <el-input
            v-model="addForm.order_phone"
            :disabled="currentUserInfo.role !== '管理员'"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单地址" prop="order_address">
          <el-input v-model="addForm.order_address"></el-input>
        </el-form-item>
        <el-form-item label="订单方式" prop="order_style">
          <el-input v-model="addForm.order_style"></el-input>
        </el-form-item>
        <el-form-item label="订单状态" prop="order_status">
          <!-- <el-input v-model="addForm.order_status"></el-input> -->
          <el-select v-model="addForm.order_status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrder">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改订单的对话框 -->
    <el-dialog
      title="修改订单"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="订单名称" prop="order_name">
          <el-input v-model="editForm.order_name"></el-input>
        </el-form-item>
        <el-form-item label="订单日期" prop="order_date">
          <!-- <el-input v-model="editForm.order_date"></el-input> -->
          <el-date-picker
            v-model="editForm.order_date"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单数量" prop="order_num">
          <el-input v-model="editForm.order_num"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="order_username">
          <el-input v-model="editForm.order_username"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="order_phone">
          <el-input v-model="editForm.order_phone"></el-input>
        </el-form-item>
        <el-form-item label="订单地址" prop="order_address">
          <el-input v-model="editForm.order_address"></el-input>
        </el-form-item>
        <el-form-item label="订单方式" prop="order_style">
          <el-input v-model="editForm.order_style"></el-input>
        </el-form-item>
        <el-form-item label="订单状态" prop="order_status">
          <!-- <el-input v-model="addForm.order_status"></el-input> -->
          <el-select v-model="editForm.order_status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editOrderInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Order',
  data() {
    // 自定义验证手机号的规则
    var checkphone = (rules, value, cb) => {
      // 验证手机号的正则表达式
      const regphone = /^1[3|4|5|7|8][0-9]{9}$/

      if (regphone.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // searchTxt: '',
      // searchValue: '',
      tableData: [],
      token: '',
      // -----------------
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      orderlist: [],
      total: 0,
      // 控制添加订单对话框的显示与隐藏
      addDialogVisible: false,
      // 添加订单的表单数据
      addForm: {
        order_name: '',
        order_date: '',
        order_num: '',
        order_username: '',
        order_phone: '',
        order_address: '',
        order_style: '',
        order_status: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        order_name: [
          { required: true, message: '请输入订单名', trigger: 'blur' },
        ],
        order_date: [
          { required: true, message: '请输入日期', trigger: 'blur' },
        ],
        order_num: [
          { required: true, message: '请输入订单数量', trigger: 'blur' },
          {
            min: 1,
            // max: 15,
            message: '数量必须大于 1',
            trigger: 'change',
          },
        ],
        order_username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' },
        ],
        order_phone: [
          { required: true, message: '请输入手机', trigger: 'change' },
          { validator: checkphone, trigger: 'change' },
        ],
        order_address: [
          { required: true, message: '请输入订单地址', trigger: 'blur' },
        ],
        order_style: [
          { required: true, message: '请输入订单类型', trigger: 'blur' },
        ],
        order_status: [
          {
            required: true,
            // type: Number,
            message: '请选择订单状态，0代表未发货，1代表已发货',
            trigger: 'change',
          },
        ],
      },
      // 订单状态选择
      options: [
        {
          value: '0',
          label: '未发货',
        },
        {
          value: '1',
          label: '已发货',
        },
      ],
      // 控制修改订单对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的 验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' },
        ],
      },
      // 控制分配订单对话框的显示与隐藏
      setStatusDialogVisible: false,
      // 需要被分配订单（那一行）的用户信息
      userInfo: {},
      // 所有订单的数据列表
      statusList: [],
      // 已选中的订单id值
      selectedRoled: '',
    }
  },
  created() {
    this.getOrderList()
    console.log(this.currentUserInfo, 'currentUserInfo')
    this.addForm.order_username = this.currentUserInfo.username
    this.addForm.order_phone = this.currentUserInfo.phone
  },
  computed: {
    currentUserInfo() {
      return this.$store.state.userInfo
    },
  },
  methods: {
    // 获取所有用户信息
    getOrderList() {
      this.$http
        .get('/myApi/order/orderinfoAll', {
          params: this.queryInfo,
        })
        .then((res) => {
          console.log(res.data, '00000000000')
          if (res.data.code == 200) {
            res.data.data.filter((item) => {
              item.order_date = item.order_date.split('').splice(0, 10).join('')
              item.order_status = item.order_status == 0 ? '未发货' : '已发货'
            })
            this.orderlist = res.data.data
            this.total = res.data.total
          }
        })
    },
    // 修改对话框
    async showEditDialog(id) {
      // 根据传进来的id 发起 axios请求，得到对用户的信息
      const { data: res } = await this.$http.get('/myApi/order/orderinfo/' + id)
      console.log(res, '???????')
      if (res.code !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.$message.success('查询用户信息成功')
      // 请求成功后将用户的信息保存到 data中
      this.editForm = res.data
      this.editForm.order_status =
        this.editForm.order_status == 0 ? '未发货' : '已发货'
      // this.selectedRoled = this.editForm.role
      // 在展示对话框之前， 获取所有的订单的列表
      // const { data: res1 } = await this.$http.get('/myApi/order/status')

      // if (res1.code !== 200) {
      //   return this.$message.error('获取订单状态列表失败！')
      // }
      // console.log(res1.data, 'status stauts')
      // this.statusList = res1.data

      this.editDialogVisible = true
      // console.log(id)
    },
    // 监听修改订单对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //修改订单信息并提交
    editOrderInfo() {
      // validate()是提交前 对整个表单进行校验的方法
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        console.log(this.editForm.order_status, 'zzzzzzzzzzzzzzzzzz')
        // this.editForm.order_status =
        //   this.editForm.order_status == '未发货' ? 0 : 1
        // 可以发起修改订单的网络请求
        const { data: res } = await this.$http.post(
          '/myApi/order/orderinfo/' + this.editForm.order_id,
          this.editForm
        )
        console.log(res)
        if (res.code !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        // 隐藏修改订单的对话框
        this.editDialogVisible = false
        // 重新渲染数据
        this.getOrderList()
        // 提示修改成功
        this.$message.success('更新用户信息成功')
      })
    },
    // 根据id 删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) // cancel
      // 如果用户点击确认 删除，则返回值为 字符串 confirm
      // 如果用户点击取消 删除，则返回值为 字符串 cancel
      // console.log(confirmResult) // Promise对象
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除!')
      }
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete(
        '/myApi/order/orderinfo/' + id
      )

      if (res.code !== 200) {
        return this.$message.error('删除用户信息失败!')
      }
      this.$message.success('删除用户信息成功')
      // 重新渲染列表
      this.getOrderList()
    },
    // 查看订单运输状态
    async setStatus(userInfo) {
      this.userInfo = userInfo
      // 将订单名称 传到物流管理界面，用户查询订单运输状态
      this.$router.push(
        `/home/logistics?order_name=${this.userInfo.order_name}`
      )
      sessionStorage.setItem('activePath', '/home/logistics')
      // this.activePath = activePath
      // // 在展示对话框之前， 获取所有的订单的列表
      // const { data: res } = await this.$http.get('/myApi/order/status')

      // if (res.code !== 200) {
      //   return this.$message.error('获取订单列表失败！')
      // }
      // console.log(res.data, 'role  role')
      // this.statusList = res.data

      // this.setStatusDialogVisible = true
    },
    // 点击 分配订单对话框的‘确认’ 按钮
    async saveRoleInfo() {
      // if (!this.selectedRoled) {
      //   return this.$message.error('请选择要分配的订单状态！')
      // }

      const { data: res } = await this.$http.get(
        `/myApi/order/status/${this.userInfo.order_id}`,
        {
          params: { role: this.selectedRoled },
        }
      )
      if (res.code !== 200) {
        return this.$message.error('更新订单失败！')
      }
      this.$message.success('更新订单成功')
      // 重新渲染列表数据
      this.getOrderList()
      // 隐藏对话框
      this.setStatusDialogVisible = false
    },
    // 监听分配订单对话框的关闭事件
    setStatusDialogClosed() {
      this.selectedRoled = ''
      this.userInfo = {}
    },
    // 监听添加订单对话框的关闭事件
    addDialogClosed() {
      // 拿到对话框的引用，调用自身的resetFields方法，重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 添加订单信息
    addOrder() {
      this.$refs['addFormRef'].validate((valid) => {
        // 校验失败
        if (!valid) return console.log('添加订单信息失败!!')
        console.log(this.addForm.order_date)
        // this.addForm.order_date = this.addForm.order_date
        //   .split('')
        //   .splice(0, 10)
        //   .join('')
        // 添加订单信息
        this.$http
          .post('/myApi/order/addOrderinfo', this.addForm)
          .then((res) => {
            console.log(res.data)
            if (res.data.code !== 200) {
              this.$message.warning('添加失败，用户名或密码错误')
            } else {
              this.$message.success('添加订单成功')
              // 隐藏添加订单的对话框
              this.addDialogVisible = false
              this.getOrderList()
            }
          })
      })
    },
    // 分页=========
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      console.log(this.queryInfo.pagesize, 'pagesize')
      this.getOrderList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      console.log(this.queryInfo.pagenum, 'pagenum')
      this.getOrderList()
    },
    // 监听 switch 开关状态的变化
    async userStateChanged(userinfo) {
      // console.log(userinfo)
      // const { data: res } = await this.$http.put(
      //   `users/${userinfo.id}/state/${userinfo.mg_state}`
      // )
      // if (res.meta.status !== 200) {
      //   userinfo.mg_state = !userinfo.mg_state
      //   return this.$message.error('更新用户状态失败')
      // }
      this.$message.success('更新用户状态成功')
    },
    filterTag(value, row) {
      return row.order_status === value
    },
  },
}
</script>

<style lang="less" scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
